﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.DataInterfaces;
using MovieRental.EfRepositoryLibrary.Mappers;
using MovieRental.GeneralDataExceptions;

namespace MovieRental.EfRepositoryLibrary
{
    public class EfMovieRepository : EfRepository<MovieInfo, Guid, Movie, Movie>, IMovieRepository
    {
        public EfMovieRepository(string connectionString)
            : base(connectionString)
        {
            _mapper = new MovieMapper();
        }

        public override void Delete(Guid id)
        {
            using (var context = CreateContext())
            {
                var editionRepository = new EfEditionRepository(_connectionString);
                foreach (var edition in context.Editions.Where(x => x.MovieId == id))
                    editionRepository.Delete(edition.Id);
            }
            base.Delete(id);
        }

        public bool MovieExists(Guid id)
        {
            using (var context = CreateContext())
            {
                try
                {
                    return context.Movies.Any(x => x.Id == id);
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Connection error.", ex);
                }
            }
        }
    }
}
